package com.bawei.detail

import android.graphics.Color
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.aspectj.CheckLoginState
import com.bawei.base.RoutePath
import com.bawei.common.entity.MovieVideoEntity
import com.bawei.common.event.CustomEvent
import com.bawei.common.event.LiveDataBus
import com.bawei.common.event.LiveDataBusEvent
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.detail.adapter.DetailViewPagerAdapter
import com.bawei.detail.databinding.ActivityDetailBinding
import com.bawei.detail.entity.DanmuEntity
import com.bawei.detail.entity.TabEntity
import com.bawei.detail.intent.DetailViewIntent
import com.bawei.detail.state.DetailUiState
import com.bawei.detail.vm.DetailViewModel
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import java.text.SimpleDateFormat

@Route(path = RoutePath.PATH_DETAIL_PAGE)
@AndroidEntryPoint
class DetailActivity : BaseMviActivity<ActivityDetailBinding>() {

    @Autowired lateinit var movieEntity: MovieVideoEntity

    private val mViewModel: DetailViewModel by viewModels()

    private var mMoviePlayer: StandardGSYVideoPlayer? = null
    private var tabList = arrayListOf<CustomTabEntity>(TabEntity("简介", 0, 0))
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPagerAdapter: DetailViewPagerAdapter
    private lateinit var mDanmuContext: DanmakuContext


    override fun getLayoutId(): Int = R.layout.activity_detail

    override fun initViews() {
        ARouter.getInstance().inject(this)
        //初始化GSYPlayer
        mMoviePlayer = mDataBinding.moviePlayer
        mMoviePlayer?.apply {
            setUp(movieEntity.videopath, true, "")
            backButton.visibility = View.GONE
        }

        tabList.add(TabEntity("评论", 0, 0))
        mDataBinding.tabLayout.setTabData(tabList)

        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_DETAIL_INTRODUCE).withString("userId", movieEntity.userid).withInt("videoTypeId", movieEntity.videotypeid).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_DETAIL_COMMEND).withString("itemId", movieEntity.userid).navigation() as Fragment)

        mPagerAdapter = DetailViewPagerAdapter(fragments, supportFragmentManager, lifecycle)
        mDataBinding.vp2.apply {
            offscreenPageLimit = 1
            adapter = mPagerAdapter
        }

        //显示弹幕发布布局
        mDataBinding.tvDanmu.setOnClickListener {
            mDataBinding.llDanmuLayout.visibility = View.VISIBLE
        }

        //发送弹幕的点击事件
        mDataBinding.ivDanmuSend.setOnClickListener {
            var danmuContent = mDataBinding.etDanmuInput.editableText.toString().trim()
            if (danmuContent.isNotEmpty()){
                sendVideoDanmu(danmuContent)
            }
        }

        //设置CommonTabLayout与ViewPager2关联
        mDataBinding.tabLayout.setOnTabSelectListener(object : OnTabSelectListener{
            override fun onTabSelect(position: Int) {
                mDataBinding.vp2.currentItem = position
            }
            override fun onTabReselect(position: Int) { }
        })

        mDataBinding.vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                mDataBinding.tabLayout.currentTab = position
                if (position == 1){
                    (fragments[1] as CommendFragment).loadCommendListById("7040684506063307271")
                }

            }
        })

        //初始化弹幕
        initVideoDanmu()

        //订阅视频列表相关操作
        LiveDataBus.with<LiveDataBusEvent>("movie_detail_options").observe(this@DetailActivity){
            handLiveDataEvent(it)
        }

    }

    /**
     * 初始化弹幕
     */
    private fun initVideoDanmu(){
        //创建弹幕上下文
        mDanmuContext = DanmakuContext.create()
        //准备弹幕
        val overlappingEnablePair: MutableMap<Int, Boolean> = HashMap()
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_RL] = true
        overlappingEnablePair[BaseDanmaku.TYPE_FIX_TOP] = true
        mDanmuContext.setDuplicateMergingEnabled(false).setScrollSpeedFactor(1.2f)
            .setScaleTextSize(1.2f)
            .setCacheStuffer(null, null)
            .preventOverlapping(overlappingEnablePair)
        mDataBinding.danmuView.prepare(object : BaseDanmakuParser(){
            override fun parse(): IDanmakus {
              return Danmakus()
            }
        }, mDanmuContext)
        //设置弹幕回调事件
//        mDataBinding.danmuView.setCallback(object : DrawHandler.Callback{
//            override fun prepared() { }
//
//            override fun updateTimer(timer: DanmakuTimer?) { }
//
//            override fun danmakuShown(danmaku: BaseDanmaku?) { }
//
//            override fun drawingFinished() { }
//        })

    }


    /**
     * 发送弹幕信息
     */
    @CheckLoginState
    private fun sendVideoDanmu(msg: String){
        val userToken = MMKV.defaultMMKV().decodeString("token", "")
        if (userToken.isNullOrEmpty()){
            ARouter.getInstance().build(RoutePath.PATH_LOGIN_PAGE).navigation()
            return
        }
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val timeMillis = System.currentTimeMillis()
        val newTime = simpleDateFormat.format(timeMillis)
        val userId = MMKV.defaultMMKV().decodeInt("userId")
        lifecycleScope.launch {
            mViewModel.channel.send(DetailViewIntent.PublishDanmuMsg(
                DanmuEntity(
                    msg,
                    newTime,
                    0,
                    "",
                    0,
                    0,
                    "6984351555034022414",
                    "",
                    userId
                )
            ))
        }
    }

    private fun handLiveDataEvent(event: LiveDataBusEvent) {
        movieEntity = event.data as MovieVideoEntity
        when(event.type){
            1 ->{
                mMoviePlayer?.setUp(movieEntity.videopath, true, "")
                mMoviePlayer?.startPlayLogic()
            }
        }
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(DetailViewIntent.LoadBulletScreenInfo(0, "6984351555034022414"))
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is DetailUiState.PublishDanmuMsgSuccess -> sendDanmuSuccess(it.data)
                is DetailUiState.PublishDanmuMsgFail -> showToastMsg(it.msg)
                is DetailUiState.LoadBulletScreenInfoSuccess -> {
                    val danmuList = mutableListOf<String>()
                    it.data.forEach {
                        danmuList.add(it.content)
                    }
                    addDanmakuList(danmuList)
                }
                is DetailUiState.LoadBulletScreenInfoFail -> showToastMsg(it.msg)
                else -> {}
            }
        }
    }

    //20250215 游戏鸿蒙-i视频-10-性能升级-多版本兼容 获取历史评论
    private fun addDanmakuList(danmuList: MutableList<String>) {
        for (danmu in danmuList) {
            addDanmaku(danmu)
        }
    }

    //20250215 游戏鸿蒙-i视频-10-性能升级-多版本兼容 获取历史评论
    private fun addDanmaku(text: String) {
        if (text.isNotEmpty()){
            val danmaku: BaseDanmaku =
                mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
            danmaku.text = text
            danmaku.padding = 10
            danmaku.textSize = 40f
            danmaku.textColor = Color.RED
            danmaku.time = 1200
            mDataBinding.danmuView.addDanmaku(danmaku)
            mDataBinding.danmuView.start()
        }
    }

    //20250216 游戏鸿蒙-i视频-10-性能升级-多版本兼容 发送评论
    private fun sendDanmuSuccess(data: DanmuEntity) {
        //清除历史弹幕
        mDataBinding.danmuView.apply {
            clear()
            removeAllDanmakus(false)
        }

        //创建弹幕实体对象
        val danmakuEntity = mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
            text = data.content
            textSize = 30f
            textColor = Color.YELLOW
            padding = 10
            time = 500 //延迟时间
        }
        mDataBinding.danmuView.addDanmaku(danmakuEntity)

        //启动弹幕动画
        mDataBinding.danmuView.start()

        //清空输入框
        mDataBinding.etDanmuInput.setText("")
        mDataBinding.llDanmuLayout.visibility = View.GONE
    }


//    override fun handEvent(event: CustomEvent) {
//        movieEntity = event.data as MovieVideoEntity
//        when(event.type){
//            1 ->{
//                mMoviePlayer?.setUp(movieEntity.videopath, true, "")
//                mMoviePlayer?.startPlayLogic()
//            }
//        }
//    }


    override fun onResume() {
        mMoviePlayer?.startPlayLogic()
        super.onResume()
    }

    override fun onPause() {
        mMoviePlayer?.onVideoPause()
        mDataBinding.danmuView.apply {
            clear()
            removeAllDanmakus(true)
        }
        super.onPause()
    }


    override fun onDestroy() {
        mMoviePlayer?.release()
        mMoviePlayer = null
        super.onDestroy()
    }


}